<template>
	<div>
		<div class="leftContent">
			<el-scrollbar :max-height="maxHeight">
				<box class="mb-3" :wvalueth="480" :title="'数据管理'">
					<div class="mb-1">
						<p class="font-lan-gray-60">地图管理：</p>
						<el-row :gutter="16">
							<el-col :span="12">
								<coverage v-model="data.select" :placeholder="'图层管理'" :options="data.coverage" @change="slecetChange" />
							</el-col>
							<el-col :span="12">
								<maptype />
							</el-col>
						</el-row>
					</div>
					<div class="mb-1">
						<p class="font-lan-gray-60">气象管理：</p>
						<el-row :gutter="16">
							<el-col :span="24">
								<scSelect v-model="data.weather" :placeholder="'气象格点'" :options="data.weathers" @change="slecetChange" :clear="true"/>
							</el-col>
							<!-- <el-col :span="12">
								<scSelect v-model="data.select" :placeholder="'种植作物'" :options="data.coverage" @change="slecetChange" />
							</el-col> -->
						</el-row>
					</div>
					<div>
						<p class="font-lan-gray-60">数据范围：</p>
						<scCascader v-model="data.cascader" :placeholder="'地址管理'" :options="storage.state.area" :label="'name'"
							:value="'id'" @change="acscaderChange" />
					</div>
				</box>
			</el-scrollbar>
		</div>
		<div class="rightContent d-flex">
      <div>
        <div v-if="data.hint == 0 || data.hint == 4" class="mr-3 text-center">
          <p style="color:#993706">43℃</p>
          <img :src="colorBar" alt="" style="height:200px;transform: rotate(180deg);">
          <p style="color:#042B66">-10℃</p>
        </div>
        <div v-if="data.hint == 1" class="mr-3 text-center">
          <p style="color:#993706">900pa</p>
          <img :src="colorBar" alt="" style="height:200px;transform: rotate(180deg);">
          <p style="color:#042B66">840pa</p>
        </div>
        <div v-if="data.hint == 2" class="mr-3 text-center">
          <p style="color:#993706">40km/h</p>
          <img :src="colorBar" alt="" style="height:200px;transform: rotate(180deg);">
          <p style="color:#042B66">0km/h</p>
        </div>
        <div v-if="data.hint == 3" class="mr-3 text-center">
          <p style="color:#042B66">70mm</p>
          <img :src="colorBar" alt="" style="height:200px">
          <p style="color:#993706">0mm</p>
        </div>
        <div v-if="data.hint == 5" class="mr-3 text-center">
          <p style="color:#042B66">120%</p>
          <img :src="colorBar" alt="" style="height:200px">
          <p style="color:#993706">30%</p>
        </div>
      </div>
			<el-scrollbar :max-height="maxHeight">
				<box class="mb-3" :width="480" :title="'气象监测'">
					<decorate1 class="mb-3">
            <div class="d-flex">
              <div class="d-flex ai-center">
                <img :src="averageTemperature" alt="">
                <span class="font-lan ml-3">今日均温：</span>
              </div>
              <div>
                <span class="font-num-l">
                  <countUp
                      :end-val="(parseFloat(data.dataInfo.maxTem) + parseFloat(data.dataInfo.minTem))/2"
                      :options="{ duration: 1 }"
                    />
                </span>
                <span class="font-lan">℃</span>
              </div>
            </div>
          </decorate1>
          <decorate1>
            <div class="d-flex">
              <div class="d-flex ai-center">
                <img :src="sunshine" alt="">
                <span class="font-lan ml-3">太阳日长：</span>
              </div>
              <div>
                <span class="font-num-l">
                  <countUp :end-val="moment(data.dataInfo.date + ' ' + data.dataInfo.sunset).diff(moment(data.dataInfo.date + ' ' + data.dataInfo.sunrise), 'hour')"/>
                </span>
                <span class="font-lan">H</span>
              </div>
            </div>
          </decorate1>
				</box>
				<box class="mb-3" :width="480" :title="'气温趋势'">
          <lineChartC :data="data.temperatureData" />
				</box>
				<box :width="480" :title="'日长趋势'">
          <lineChartC :data="data.radiationData" />
				</box>
			</el-scrollbar>
		</div>
    <daysBar :data="{dateList:data.dateList,forecast:data.forecast}" @timeChange="timeChange" @monthChange="monthChange"/>
	</div>
</template>
  
<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted, computed } from "vue";
import lineChartC from "@/chart/lineChart/line-curve-1";
import daysBar from '@/components/timeBar/daysBar.vue'
import mapControler from "@/components/mapContainer/mapControler";
import {
  getGridWeather,
  temperatureTrend
} from "@/public/request/http";
import moment from "moment";
import storage from '@/store'
import { calcMonthDate,getColorByTem,getColorByPressure,getColorByWindSpeed,getColorByPrecip,getColorBySoilTem,getColorBySoilHumidity } from "@/utils/common";
export default defineComponent({
	components: {
    lineChartC,
    daysBar
	},
	setup() {
		//变量
		// const maxHeight = ref(window.innerHeight-160+'px')
		const maxHeight = computed(() => window.innerHeight - 160 + 'px')
		const data: any = reactive({
			coverage: [],
			select: null,
			pullDatas: [],
			pullData: [],
			cascader: [],
      weather:null,
      weathers:[{label: "气温",value:0},{label: "气压",value:1},{label: "风速",value:2},{label: "降水",value:3},{label: "土壤温度",value:4},{label: "土壤湿度",value:5}],
      dataInfo: {},
      temperatureData: {
        xAxis: [],
        series: [],
        unit: "℃",
      },
      radiationData: {
        xAxis: [],
        series: [],
        unit: "h",
      },
      dateList: [],
      forecast:4,
      hint:null,
      date:moment().format('YYYY-MM-DD')
		});

    const averageTemperature = require("@/assets/img/averageTemperature.png");
    const colorBar = require("@/assets/img/colorBar.png");
    const sunshine = require("@/assets/img/sunshine.png");
		
		// 生命周期
		onMounted(async () => {
			mapControler.mapReSet();
			getTemperatureTrend(data.date)
      let endDate = moment().add(data.forecast, "days").format("YYYY-MM-DD")>moment().endOf("month").format("YYYY-MM-DD")?moment().endOf("month").format("YYYY-MM-DD"):moment().add(data.forecast, "days").format("YYYY-MM-DD")
      data.dateList = calcMonthDate(moment().format('YYYY-MM'),false,endDate).map(item=>moment(item).format('DD'))
		});

		onUnmounted(() => {
			//
			mapControler.mapReSet();

		});

		//methods
    const getTemperatureTrend = async (date) => {
      try {
        let res = await temperatureTrend({day:date})
        data.dataInfo =  res[0]
        let xAxis = []
        let series = [
          { name: "最高温", data: [], color: "#23D0C4" },
          { name: "最低温", data: [], color: "rgba(41, 139, 204, 1)" },
        ]
        let series1 = [{ name: "日长", data: [], color: "#ccab29" }]
        res.forEach(item => {
          xAxis.push(moment(item.date).format('MM-DD'))
          series[0].data.push(item.maxTem)
          series[1].data.push(item.minTem)
          series1[0].data.push(moment(item.date + ' ' + item.sunset).diff(moment(item.date + ' ' + item.sunrise), 'hour'))
        });
        data.temperatureData.xAxis = xAxis
        data.temperatureData.series = series
        data.radiationData.xAxis = xAxis
        data.radiationData.series = series1
      } catch (error) {
        
      }
    }

    const getGridWeatherData = async (val) => {
      mapControler.mapReSet();
      const lngDiff = 0.031185
      const latDiff = 0.022595
      try {
        let res = await getGridWeather({time:data.date});
        data.hint = val
        res.forEach((item) => {
          item.type = (val == 4 || val == 5) ? '土壤' : '气象'
          item.pointList = [];
          item.pointList.push({
            lng: parseFloat(item.longitude) - lngDiff,
            lat: parseFloat(item.latitude) + latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.longitude) - lngDiff,
            lat: parseFloat(item.latitude) - latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.longitude) + lngDiff,
            lat: parseFloat(item.latitude) - latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.longitude) + lngDiff,
            lat: parseFloat(item.latitude) + latDiff,
          });
          item.fillColor = getColorByType(val,item)
          item.fillOpacity = 0.6
          mapControler.drawArea(item);
        });
      } catch (error) {}
    };

    const getColorByType = (index,val) => {
      let color = ''
      switch (index) {
        case 0:
          color = getColorByTem(val.temperature);
          break;
        case 1:
          color = getColorByPressure(val.pressure);
          break;
        case 2:
          color = getColorByWindSpeed(val.windSpeed);
          break;
        case 3:
          color = getColorByPrecip(val.precip);
          break;
        case 4:
          color = getColorBySoilTem(val.soilTemperature10cm)
          break;
        case 5:
          color = getColorBySoilHumidity(val.soilHumidity10cm);
          break;
        default:
          break;
      }
      return color
    }

		const timeChange = (val) => {
      //
      data.date = val
      getTemperatureTrend(val)
      if(data.hint != null){
        mapControler.mapReSet()
        getGridWeatherData(data.hint)
      }
    };

    const monthChange = async (val) =>{
      let endDate = moment().add(data.forecast, "days").format("YYYY-MM-DD")>moment(val).endOf("month").format("YYYY-MM-DD")?moment(val).endOf("month").format("YYYY-MM-DD"):moment().add(data.forecast, "days").format("YYYY-MM-DD")
      data.dateList = calcMonthDate(val, false, endDate).map(item => moment(item).format('DD'))
      let activeIndex = 0
      if(moment(val).format('YYYY-MM')<moment().format('YYYY-MM')){
        activeIndex = data.dateList.length - 1
      }else if(moment(val).format('YYYY-MM') == moment().format('YYYY-MM')){
        activeIndex = data.dateList.length - (1+parseInt(data.dateList[data.dateList.length - 1])-parseInt(moment().format('DD')))
      }else{
        activeIndex = 0
      }
      data.date = val+'-'+data.dateList[activeIndex]
      getTemperatureTrend(data.date)
      if(data.hint != 0){
        mapControler.mapReSet()
        getGridWeatherData(data.hint)
      }
    }

		const slecetChange = (e) => {
      console.log(e);
      
      data.hint = e
      if(e != null){
        getGridWeatherData(data.hint)
      }else{
        mapControler.mapReSet()
      }
        
      
		}

		const acscaderChange = (e) => {
			console.log(data.cascader);
		}

		// return
		return {
			data,
			slecetChange,
			acscaderChange,
			moment,
			maxHeight,
			storage,
      timeChange,
      monthChange,
      averageTemperature,
      colorBar,
      sunshine
		};
	},
});
</script>
  
<style lang="scss" scoped>
@import "@/assets/scss/index.scss";

</style>
  